package com.hb.trade.server.project.notice.manager;

import cn.hutool.core.collection.CollUtil;
import com.hb.core.pojo.enums.DeployStatusEnum;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.core.pojo.project.notice.dto.NoticeDTO;
import com.hb.core.pojo.project.notice.entity.Notice;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.trade.server.project.notice.service.NoticeBidSectionService;
import com.hb.trade.server.project.notice.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 保存控制价公告
 *
 * @author zhaojk
 */
@Service
@Slf4j
public class NoticeSaveLimitPrice extends NoticeSaveSection {
    protected final NoticeBidSectionService noticeBidSectionService;

    public NoticeSaveLimitPrice(NoticeService noticeService,
                                NoticeBidSectionService noticeBidSectionService) {
        super(noticeService);
        this.noticeBidSectionService = noticeBidSectionService;
    }

    /**
     * 对公告执行保存
     *
     * @param noticeDTO
     * @return 保存公告结果, true: 保存成功, false: 保存失败
     */
    @Override
    public boolean saveNotice(NoticeDTO noticeDTO) {
        // 处理公告主体信息
        Long noticeId = noticeDTO.getId();
        if (noticeId != null) {
            DeployStatusEnum status = getStatus(noticeId);
            if (status == DeployStatusEnum.DEPLOYED) {
                log.warn("无法修改已发布的公告");
                return false;
            }

            Notice rawNotice = noticeService.getById(noticeId);
            noticeDTO.to(rawNotice);
            noticeService.updateById(rawNotice);
        } else {
            // 公告发布状态默认为未发布
            noticeDTO.setDeployStatus(DeployStatusEnum.UN_DEPLOYED.getCode());
            noticeDTO.buildBaseData(1);
            noticeService.save(noticeDTO);
        }

        List<BidSectionDTO> sections = noticeDTO.getBidSectionList();
        List<Long> sectionIds = CollUtil.map(sections, MPCommonEntity::getId, true);
        if (CollUtil.isNotEmpty(sectionIds)) {
            // 更新标段, 公告中间表
            noticeBidSectionService.updateNoticeSections(noticeDTO.getId(), sectionIds);
        }
        return true;
    }

    @Override
    public String deploy(Notice notice) {
        return null;
    }
}
